package com.zjbbkj.baibai.common.utils.wanli;

import java.util.*;

/**
 * @program: boot-parent
 * @author: Mr.WanLi
 * @create: 2019-07-01 14:05
 **/

public class MapUtils {

    public static void main(String[] args) {
        Map<String, String> map = new TreeMap<String, String>(
                new Comparator<String>() {
                    public int compare(String obj1, String obj2) {
                        // 降序排序
                        return obj2.compareTo(obj1);
                    }
                });
        map.put("c", "ccccc");
        map.put("a", "aaaaa");
        map.put("b", "bbbbb");
        map.put("d", "ddddd");

        Set<String> keySet = map.keySet();
        Iterator<String> iter = keySet.iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            System.out.println(key + ":" + map.get(key));
        }
    }


    public static Map<String, String> SortMap(LinkedHashMap<String, String> map) {
        List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }
        });
        String string = String.valueOf(list.get(0)) + String.valueOf(list.get(1));
        System.out.println(string);
        return map;
    }

    public static Map<Object, Object> sortMapByKey(Map<Object, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<Object, Object> sortMap = new TreeMap<>(new MapKeyComparator());
        sortMap.putAll(map);
        return sortMap;
    }

    public static class MapKeyComparator implements Comparator<Object> {
        @Override
        public int compare(Object o1, Object o2) {
            return Integer.parseInt(String.valueOf(o1)) - Integer.parseInt(String.valueOf(o2));
        }
    }
}
